package lapsnake.model.misc;

import java.util.List;

import lapsnake.model.*;
import lapsnake.model.bounceback.StringNode;
import lapsnake.model.data.*;
import lapsnake.model.expr.LapName;
import lapsnake.py.ast.ASTHelperFactory; import java.beans.PropertyVetoException;

import org.python.antlr.ast.*;

/**Wrapper class with helper functions for alias nodes*/
public class LapAlias extends LapNode {
	public final VetoableProperty<String> name = new VetoableProperty<>(String.class);
	public final OptionalChild<LapName> asName = new OptionalChild<>(this, LapName.class);
	
	public LapAlias(PyAST pyAST, ChildField<? super LapAlias> parent, alias node) throws PropertyVetoException {
		super(pyAST, parent, node);
		name.setInternal(node.getInternalName());
		ASTHelperFactory.makeHelper(pyAST, asName, node.getInternalAsnameNode());
		
		//Alias handling in jython seems to be broken...
		//Sometimes, there are name nodes, and then the alias node itself has no usable data.
		//Other times, there are no names nodes, but the alias node itself then has values set on it.
		List<Name> nameNodes = node.getInternalNameNodes();
		if(nameNodes != null && nameNodes.size() > 0)
		{
			int charStart = Integer.MAX_VALUE;
			int charEnd = 0;
			for (Name n : nameNodes)
			{
				charStart = Math.min(charStart, n.getCharStartIndex());
				charEnd = Math.max(charEnd, n.getCharStopIndex());
			}
			node.setCharStartIndex(charStart);
			node.setCharStopIndex(charEnd);
		}
		else
		{
			assert node.getCharStartIndex() >= 0;
		}
		
		buildTextNodes(node);
	}

	public LapAlias(PyAST pyAST, ChildField<? super LapAlias> field, String importName) throws PropertyVetoException
	{
		super(pyAST, field, null);
		name.setInternal(importName);
		setTextNodes(new StringNode(importName));
	}
}
